package com.bayihouse.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class AgeConverter implements Converter<Date> {

    public Class supportJavaTypeKey() {
        return Date.class;
    }

    public static final Map<String, String> dateMap;

    static {
        dateMap = new HashMap<>();
        dateMap.put("^\\d{4}-\\d{2}-\\d{2}$", "yyyy-MM-dd");
        dateMap.put("^\\d{4}年\\d{2}月\\d{2}日$", "yyyy年MM月dd日");
        dateMap.put("^\\d{4}年\\d{2}月\\d{2}日 \\d{2}时\\d{2}分\\d{2}秒$", "yyyy年MM月dd日 hh时mm分ss秒");
        dateMap.put("^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$", "yyyy-MM-dd hh:mm:ss");
    }


    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.NUMBER;
    }


    public Date convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                  GlobalConfiguration globalConfiguration) throws ParseException {
        int age;
        if (cellData.getType() == CellDataTypeEnum.NUMBER) {
            age = cellData.getNumberValue().intValue();
        }else{
            age = Integer.parseInt(cellData.getStringValue());
        }
        Calendar calendar = Calendar.getInstance();
        int year = calendar.YEAR;
        int month = calendar.MONTH;
        int day = calendar.DAY_OF_MONTH;
        calendar.set(year - age, month, day);
        return calendar.getTime();
    }
}
